<template>
  <Modal
    class="game-review-modal"
    v-if="isVisible"
    @close="close"
  >
    <div class="review-header">
      <h2>🎭 游戏复盘分析</h2>
      <div class="review-stats">
        <span class="stat-item">总轮次: {{ totalRounds }}</span>
        <span class="stat-item">总事件: {{ totalEvents }}</span>
        <span class="stat-item">参与玩家: {{ totalPlayers }}</span>
      </div>
    </div>

    <div class="review-content">
      <!-- 时间轴视图 -->
      <div class="timeline-section">
        <h3>🕐 游戏时间轴</h3>
        <div class="timeline-container">
          <div 
            v-for="phase in gamePhases" 
            :key="phase.round"
            class="timeline-phase"
            :class="phase.type"
          >
            <div class="phase-header">
              <span class="phase-icon">{{ phase.icon }}</span>
              <span class="phase-name">{{ phase.name }}</span>
              <span class="phase-count">({{ phase.events.length }})</span>
            </div>
            <div class="phase-events">
              <div 
                v-for="event in phase.events.slice(0, 3)" 
                :key="event.id"
                class="timeline-event"
              >
                <span class="event-icon">{{ getEventIcon(event.action) }}</span>
                <span class="event-summary">{{ event.summary }}</span>
              </div>
              <div v-if="phase.events.length > 3" class="more-events">
                +{{ phase.events.length - 3 }} 更多事件
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 玩家信息矩阵 -->
      <div class="matrix-section">
        <h3>👥 玩家信息矩阵</h3>
        <div class="matrix-tip" v-if="gamePhases.length > 5">
          💡 数据较多时可以横向滚动查看
        </div>
        <div class="matrix-container">
          <table class="info-matrix">
            <thead>
              <tr>
                <th class="player-header">玩家</th>
                <th 
                  v-for="phase in gamePhases" 
                  :key="phase.round"
                  class="phase-header-cell"
                  :class="phase.type"
                >
                  {{ phase.shortName }}
                </th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="player in playerMatrix" :key="player.name">
                <td class="player-cell">
                  <div class="player-info">
                    <span class="player-name">{{ player.name }}</span>
                    <span class="player-role" v-if="player.role">{{ player.role }}</span>
                  </div>
                </td>
                <td 
                  v-for="phase in gamePhases" 
                  :key="phase.round"
                  class="matrix-cell"
                >
                  <div class="cell-content">
                    <div 
                      v-for="info in player.phaseInfo[phase.round] || []" 
                      :key="info.id"
                      class="info-item"
                      :class="info.type"
                    >
                      <span class="info-icon">{{ info.icon }}</span>
                      <span class="info-text">{{ info.text }}</span>
                    </div>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- 关键统计 -->
      <div class="stats-section">
        <h3>📈 关键统计</h3>
        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-icon">💀</div>
            <div class="stat-info">
              <div class="stat-number">{{ deathCount }}</div>
              <div class="stat-label">死亡人数</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">🗳️</div>
            <div class="stat-info">
              <div class="stat-number">{{ voteCount }}</div>
              <div class="stat-label">投票次数</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">⚡</div>
            <div class="stat-info">
              <div class="stat-number">{{ abilityUseCount }}</div>
              <div class="stat-label">能力使用</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">🏷️</div>
            <div class="stat-info">
              <div class="stat-number">{{ reminderCount }}</div>
              <div class="stat-label">标记操作</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="review-footer">
      <button @click="exportReview" class="export-btn">
        📤 导出复盘报告
      </button>
      <button @click="close" class="close-btn">
        关闭
      </button>
    </div>
  </Modal>
</template>

<script>
import Modal from "./Modal";
import { mapState } from "vuex";

export default {
  name: "GameReviewModal",
  components: {
    Modal,
  },
  props: {
    isVisible: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    ...mapState(["history"]),
    ...mapState("players", ["players"]),
    
    // 总轮次数
    totalRounds() {
      const rounds = new Set();
      this.history.events.forEach(event => {
        if (event.round && event.round !== "setup") {
          rounds.add(event.round);
        }
      });
      return rounds.size;
    },
    
    // 总事件数
    totalEvents() {
      return this.history.events.length;
    },
    
    // 参与玩家数
    totalPlayers() {
      const players = new Set();
      this.players.forEach(player => {
        if (player.name) players.add(player.name);
      });
      this.history.events.forEach(event => {
        if (event.playerName) players.add(event.playerName);
      });
      return players.size;
    },
    
    // 游戏阶段时间轴
    gamePhases() {
      const phasesMap = new Map();
      
      this.history.events.forEach(event => {
        if (!event.round || event.round === "setup") return;
        
        if (!phasesMap.has(event.round)) {
          phasesMap.set(event.round, {
            round: event.round,
            name: this.getPhaseName(event.round),
            shortName: this.getPhaseShortName(event.round),
            type: this.getPhaseType(event.round),
            icon: this.getPhaseIcon(event.round),
            events: []
          });
        }
        
        phasesMap.get(event.round).events.push(event);
      });
      
      // 按时间顺序排序
      return Array.from(phasesMap.values()).sort((a, b) => {
        return this.getPhaseWeight(a.round) - this.getPhaseWeight(b.round);
      });
    },
    
    // 玩家信息矩阵
    playerMatrix() {
      const playersMap = new Map();
      
      // 初始化玩家信息
      this.players.forEach(player => {
        if (player.name) {
          playersMap.set(player.name, {
            name: player.name,
            role: player.role?.name || "",
            phaseInfo: {}
          });
        }
      });
      
      // 从历史事件中提取玩家信息
      this.history.events.forEach(event => {
        if (!event.playerName || !event.round || event.round === "setup") return;
        
        if (!playersMap.has(event.playerName)) {
          playersMap.set(event.playerName, {
            name: event.playerName,
            role: "",
            phaseInfo: {}
          });
        }
        
        const player = playersMap.get(event.playerName);
        if (!player.phaseInfo[event.round]) {
          player.phaseInfo[event.round] = [];
        }
        
        player.phaseInfo[event.round].push({
          id: event.id,
          type: this.getInfoType(event.action),
          icon: this.getEventIcon(event.action),
          text: this.getInfoText(event)
        });
      });
      
      return Array.from(playersMap.values()).sort((a, b) => a.name.localeCompare(b.name));
    },
    
    // 统计数据
    deathCount() {
      return this.history.events.filter(e => 
        e.action === "player_died" || e.action === "execution"
      ).length;
    },
    
    voteCount() {
      return this.history.events.filter(e => e.action === "vote").length;
    },
    
    abilityUseCount() {
      return this.history.events.filter(e => e.action === "role_ability").length;
    },
    
    reminderCount() {
      return this.history.events.filter(e => 
        e.action === "reminder_added" || e.action === "custom_reminder_added"
      ).length;
    }
  },
  
  methods: {
    close() {
      this.$emit("close");
    },
    
    // 英文轮次转数字映射
    getNumberFromEnglish(englishStr) {
      const numberMap = {
        "first": 1, "second": 2, "third": 3, "fourth": 4,
        "fifth": 5, "sixth": 6, "seventh": 7, "eighth": 8,
        "ninth": 9, "tenth": 10, "eleventh": 11, "twelfth": 12,
        "thirteenth": 13, "fourteenth": 14, "fifteenth": 15,
      };
      
      // 支持 round_X 格式
      const roundMatch = englishStr.match(/round_(\d+)/);
      if (roundMatch) {
        return parseInt(roundMatch[1]);
      }
      
      return numberMap[englishStr] || null;
    },

    // 获取阶段名称
    getPhaseName(round) {
      if (round === "first_night") return "首夜";
      if (round === "first_day") return "第1个白天";
      if (round === "second_night") return "第2个夜晚";
      if (round === "second_day") return "第2个白天";
      
      // 处理英文单词_night格式
      const nightMatch = round.match(/(.+)_night/);
      if (nightMatch) {
        const identifier = nightMatch[1];
        const number = this.getNumberFromEnglish(identifier);
        return number ? `第${number}个夜晚` : round;
      }
      
      // 处理英文单词_day格式
      const dayMatch = round.match(/(.+)_day/);
      if (dayMatch) {
        const identifier = dayMatch[1];
        const number = this.getNumberFromEnglish(identifier);
        return number ? `第${number}个白天` : round;
      }
      
      return round;
    },
    
    // 获取阶段简称
    getPhaseShortName(round) {
      if (round === "first_night") return "首夜";
      if (round === "first_day") return "1日";
      if (round === "second_night") return "2夜";
      if (round === "second_day") return "2日";
      
      // 处理英文单词_night格式
      const nightMatch = round.match(/(.+)_night/);
      if (nightMatch) {
        const identifier = nightMatch[1];
        const number = this.getNumberFromEnglish(identifier);
        return number ? `${number}夜` : round;
      }
      
      // 处理英文单词_day格式
      const dayMatch = round.match(/(.+)_day/);
      if (dayMatch) {
        const identifier = dayMatch[1];
        const number = this.getNumberFromEnglish(identifier);
        return number ? `${number}日` : round;
      }
      
      return round;
    },
    
    // 获取阶段类型
    getPhaseType(round) {
      if (round.includes("night")) return "night";
      if (round.includes("day")) return "day";
      return "unknown";
    },
    
    // 获取阶段图标
    getPhaseIcon(round) {
      if (round.includes("night")) return "🌙";
      if (round.includes("day")) return "☀️";
      return "⚪";
    },
    
    // 获取阶段权重（用于排序）
    getPhaseWeight(round) {
      if (round === "first_night") return 1;
      if (round === "first_day") return 2;
      if (round === "second_night") return 3;
      if (round === "second_day") return 4;
      
      // 处理英文单词_night格式
      const nightMatch = round.match(/(.+)_night/);
      if (nightMatch) {
        const identifier = nightMatch[1];
        const number = this.getNumberFromEnglish(identifier);
        return number ? number * 2 - 1 : 999;
      }
      
      // 处理英文单词_day格式
      const dayMatch = round.match(/(.+)_day/);
      if (dayMatch) {
        const identifier = dayMatch[1];
        const number = this.getNumberFromEnglish(identifier);
        return number ? number * 2 : 999;
      }
      
      return 999;
    },
    
    // 获取事件图标
    getEventIcon(action) {
      const icons = {
        wake_up: "🌙",
        vote: "🗳️",
        execution: "💀",
        role_assignment: "🎭",
        nomination: "📢",
        player_died: "💀",
        player_revived: "🔄",
        player_voteless: "🚫",
        player_vote_restored: "✅",
        player_nominated: "⚖️",
        player_nomination_cancelled: "❌",
        player_protected: "🛡️",
        player_poisoned: "☠️",
        custom: "✏️",
        reminder_added: "🏷️",
        reminder_removed: "🗑️",
        custom_reminder_added: "✏️",
        role_ability: "⚡",
        phase_change: "⚙️",
        game_start: "🎮",
        roles_assigned: "🎲",
      };
      return icons[action] || "📝";
    },
    
    // 获取信息类型
    getInfoType(action) {
      if (["player_died", "execution"].includes(action)) return "death";
      if (["vote", "nomination"].includes(action)) return "vote";
      if (["role_ability"].includes(action)) return "ability";
      if (["reminder_added", "custom_reminder_added"].includes(action)) return "reminder";
      return "normal";
    },
    
    // 获取信息文本
    getInfoText(event) {
      if (event.summary && event.summary.length < 20) {
        return event.summary;
      }
      if (event.details && event.details.length < 30) {
        return event.details;
      }
      return event.action;
    },
    
    // 导出复盘报告
    exportReview() {
      const reviewData = {
        gameStats: {
          totalRounds: this.totalRounds,
          totalEvents: this.totalEvents,
          totalPlayers: this.totalPlayers,
          deathCount: this.deathCount,
          voteCount: this.voteCount,
          abilityUseCount: this.abilityUseCount,
          reminderCount: this.reminderCount
        },
        timeline: this.gamePhases,
        playerMatrix: this.playerMatrix,
        generatedAt: new Date().toISOString()
      };
      
      const dataStr = JSON.stringify(reviewData, null, 2);
      const dataBlob = new Blob([dataStr], { type: 'application/json' });
      const url = URL.createObjectURL(dataBlob);
      
      const link = document.createElement('a');
      link.href = url;
      link.download = `血染钟楼复盘报告_${new Date().toLocaleDateString()}.json`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
      
      console.log("📤 复盘报告已导出");
    }
  }
};
</script>

<style lang="scss" scoped>
.game-review-modal {
  .review-header {
    padding: 20px;
    border-bottom: 1px solid #333;
    background: rgba(0, 0, 0, 0.3);
    
    h2 {
      margin: 0 0 10px 0;
      color: #fff;
      font-size: 24px;
    }
    
    .review-stats {
      display: flex;
      gap: 20px;
      
      .stat-item {
        padding: 5px 12px;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 15px;
        font-size: 14px;
        color: #ccc;
      }
    }
  }
  
  .review-content {
    padding: 20px;
    max-height: 70vh;
    overflow-y: auto;
    
    h3 {
      margin: 0 0 15px 0;
      color: #fff;
      font-size: 18px;
      border-bottom: 2px solid #444;
      padding-bottom: 8px;
    }
  }
  
  // 时间轴样式
  .timeline-section {
    margin-bottom: 30px;
    
    .timeline-container {
      display: flex;
      gap: 15px;
      overflow-x: auto;
      padding: 10px 0;
      
      .timeline-phase {
        min-width: 200px;
        background: rgba(255, 255, 255, 0.05);
        border-radius: 8px;
        padding: 15px;
        border-left: 4px solid #666;
        
        &.night {
          border-left-color: #4a5568;
          background: rgba(74, 85, 104, 0.1);
        }
        
        &.day {
          border-left-color: #d69e2e;
          background: rgba(214, 158, 46, 0.1);
        }
        
        .phase-header {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 10px;
          
          .phase-icon {
            font-size: 18px;
          }
          
          .phase-name {
            font-weight: bold;
            color: #fff;
          }
          
          .phase-count {
            color: #999;
            font-size: 12px;
          }
        }
        
        .phase-events {
          .timeline-event {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 5px;
            font-size: 12px;
            color: #ccc;
            
            .event-icon {
              font-size: 14px;
            }
            
            .event-summary {
              flex: 1;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }
          
          .more-events {
            font-size: 11px;
            color: #888;
            font-style: italic;
            margin-top: 5px;
          }
        }
      }
    }
  }
  
  // 矩阵样式
  .matrix-section {
    margin-bottom: 30px;
    
    .matrix-tip {
      margin: 10px 0;
      padding: 8px 12px;
      background: rgba(255, 193, 7, 0.1);
      color: #ffd43b;
      font-size: 12px;
      border-radius: 4px;
      border-left: 3px solid #ffd43b;
    }
    
    .matrix-container {
      overflow-x: auto;
      overflow-y: visible;
      max-width: 100%;
      border: 1px solid #333;
      border-radius: 8px;
      background: rgba(0, 0, 0, 0.2);
      
      // 自定义滚动条样式
      &::-webkit-scrollbar {
        height: 8px;
      }
      
      &::-webkit-scrollbar-track {
        background: rgba(255, 255, 255, 0.1);
        border-radius: 4px;
      }
      
      &::-webkit-scrollbar-thumb {
        background: rgba(255, 255, 255, 0.3);
        border-radius: 4px;
        
        &:hover {
          background: rgba(255, 255, 255, 0.5);
        }
      }
      
      .info-matrix {
        min-width: 800px; // 确保最小宽度，强制横向滚动
        border-collapse: collapse;
        background: rgba(255, 255, 255, 0.02);
        
        th, td {
          border: 1px solid #333;
          padding: 8px;
          text-align: center;
          vertical-align: top;
        }
        
        th {
          background: rgba(255, 255, 255, 0.1);
          color: #fff;
          font-weight: bold;
          position: sticky;
          top: 0;
          z-index: 10;
          
          &.player-header {
            min-width: 120px;
            left: 0;
            z-index: 11;
          }
          
          &.phase-header-cell {
            min-width: 100px;
            max-width: 120px;
            white-space: nowrap;
            font-size: 12px;
            
            &.night {
              background: rgba(74, 85, 104, 0.3);
            }
            
            &.day {
              background: rgba(214, 158, 46, 0.3);
            }
          }
        }
        
        .player-cell {
          background: rgba(255, 255, 255, 0.05);
          position: sticky;
          left: 0;
          z-index: 5;
          
          .player-info {
            text-align: left;
            
            .player-name {
              display: block;
              font-weight: bold;
              color: #fff;
              margin-bottom: 2px;
            }
            
            .player-role {
              display: block;
              font-size: 11px;
              color: #888;
            }
          }
        }
        
        .matrix-cell {
          min-width: 100px;
          max-width: 120px;
          width: 110px;
          
          .cell-content {
            .info-item {
              display: flex;
              align-items: center;
              gap: 4px;
              margin-bottom: 3px;
              font-size: 11px;
              padding: 2px 4px;
              border-radius: 3px;
              
              &.death {
                background: rgba(220, 53, 69, 0.2);
                color: #ff6b6b;
              }
              
              &.vote {
                background: rgba(0, 123, 255, 0.2);
                color: #4dabf7;
              }
              
              &.ability {
                background: rgba(40, 167, 69, 0.2);
                color: #51cf66;
              }
              
              &.reminder {
                background: rgba(255, 193, 7, 0.2);
                color: #ffd43b;
              }
              
              .info-icon {
                font-size: 10px;
              }
              
              .info-text {
                flex: 1;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              }
            }
          }
        }
      }
    }
  }
  
  // 统计样式
  .stats-section {
    .stats-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
      gap: 15px;
      
      .stat-card {
        background: rgba(255, 255, 255, 0.05);
        border-radius: 8px;
        padding: 15px;
        display: flex;
        align-items: center;
        gap: 12px;
        
        .stat-icon {
          font-size: 24px;
        }
        
        .stat-info {
          .stat-number {
            font-size: 20px;
            font-weight: bold;
            color: #fff;
          }
          
          .stat-label {
            font-size: 12px;
            color: #888;
          }
        }
      }
    }
  }
  
  .review-footer {
    padding: 20px;
    border-top: 1px solid #333;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .export-btn {
      padding: 10px 20px;
      background: #28a745;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      font-size: 14px;
      
      &:hover {
        background: #218838;
      }
    }
    
    .close-btn {
      padding: 10px 20px;
      background: #6c757d;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      font-size: 14px;
      
      &:hover {
        background: #5a6268;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .game-review-modal {
    .timeline-container {
      .timeline-phase {
        min-width: 150px;
      }
    }
    
    .matrix-container {
      // 移动端优化横向滚动
      -webkit-overflow-scrolling: touch;
      
      .info-matrix {
        min-width: 600px; // 移动端减少最小宽度
      }
    }
    
    .info-matrix {
      font-size: 11px;
      
      th, td {
        padding: 4px;
      }
      
      .matrix-cell {
        min-width: 80px;
        max-width: 100px;
        width: 90px;
      }
      
      .phase-header-cell {
        min-width: 80px;
        max-width: 100px;
      }
    }
    
    .stats-grid {
      grid-template-columns: repeat(2, 1fr);
    }
  }
}
</style>